'use strict';

var Router = require('koa-router');
var config = require('../../../config/index.js');
var dao = require('../../../dao/face_part.js');
var appUtil = require('../../../common/app_utils.js');
var errCodes = require('../../../common/err_code.js');
var counter = require('../../../dao/counter.js');

//
var __pathPrefix = config.manBaseUrl + '/v1/face/parts';
appUtil.appLog('router:' + __pathPrefix);
var router = new Router({prefix: __pathPrefix});
module.exports = router.routes();

// 部位编号
var EnumParts = config.EnumParts;

var myCounter = counter.bindCounter(counter.TypesEnum.facePart);

/**
 * 获取某个明星的面部组件
 * get /manapi/v1/face/parts?token=xxx&starid=xx
 * 是为了支持 token校验
 */
router.get('/', function*() {
  var starid = this.request.inParams.fields.starid;
  if (!starid) {
    return this.body = appUtil.ferror(errCodes.E_ARGS_INVALID, 'starid');
  }

  var result = yield dao.getByStarid(starid);
  var ret = [];
  for (var item of result) {
    ret.push({
      url: config.rootUrl + item.rurl,
      desc: item.desc,
      starid: item.starid,
      otype: item.otype,
      partid: item.partid
    });
  }
  this.body = appUtil.fout(ret);
});


/**
 * 上传 明星组件,用于新增or更新
 * post /manapi/v1/face/parts/upload
 * 管理api
 */
router.post('/upload', function*() {
  var starid = this.request.inParams.fields.starid;
  var files = this.request.inParams.files;
  if (!starid) return this.body = appUtil.ferror(errCodes.E_ARGS_INVALID, 'starid');
  if (!files) return this.body = appUtil.ferror(errCodes.E_ARGS_INVALID, ' image file');

  var file, desc;
  var result = {};
  // 眉毛
  file = files.browfile;
  desc = this.request.inParams.fields.browdesc;
  result.brow = yield __saveOrUpdate(starid, EnumParts.brow, desc, file && file.path);
  // 眼睛
  file = files.eyefile;
  desc = this.request.inParams.fields.eyedesc;
  result.eye = yield __saveOrUpdate(starid, EnumParts.eye, desc, file && file.path);
  // 鼻子
  file = files.nosefile;
  desc = this.request.inParams.fields.nosedesc;
  result.nose = yield __saveOrUpdate(starid, EnumParts.nose, desc, file && file.path);
  // 嘴巴
  file = files.mousefile;
  desc = this.request.inParams.fields.mousedesc;
  result.mouse = yield __saveOrUpdate(starid, EnumParts.mouse, desc, file && file.path);

  this.body = appUtil.fout(result);
});

/**
 * @private 设置OR更新 组件
 */
function * __saveOrUpdate(starid, otype, desc, tmpFilePath) {
  if (!desc && !tmpFilePath) {
    return {};
  }

  var pathResult = appUtil.getPath_parts(starid, otype);
  if (tmpFilePath) {
    appUtil.moveFile(tmpFilePath, pathResult.fullPath);
  }

  var part = yield dao.getByStaridAndOtype(starid, otype);
  if (part) { // 如果已经存在，则更新，否则覆盖
    console.log('part already exists');
    part.desc = desc || '';
    if (tmpFilePath) {
      part.path = pathResult.fullPath;
      part.rurl = pathResult.rurl;
    }
    yield part.save();
  } else {
    console.log('part not exists');
    var partid = yield myCounter();
    part = {
      partid: partid,
      otype: otype,
      starid: starid,
      desc: desc || ''
    };
    if (tmpFilePath) {
      part.path = pathResult.fullPath;
      part.rurl = pathResult.rurl;
    }
    yield dao.save(part);// 保存到数据库
  }
  return {
    starid: part.starid,
    otype: part.otype,
    partid: part.partid,
    url: pathResult.fullUrl
  };
}

/**
 * 重新设置order
 * post /manapi/v1/face/parts/order
 * {token:xxx,orders:[{partid:xx,order:1}, ... ]
 */
router.post('/order', function*() {
  var orders = this.request.inParams.fields.orders;
  if (!orders || !Array.isArray(orders) || orders.length === 0) {
    return this.body = appUtil.ferror(errCodes.E_ARGS_INVALID, 'orders 无效');
  }
  for (var i = 0; i < orders.length; i++) {
    var item = orders[i];
    if (!item.partid || item.order == null || typeof(item.order) === 'undefined')
      continue;

    var ret = yield dao.update({
      query: {partid: item.partid},
      update: {$set: {order: item.order}}
    });
    if (ret._error) {
      item.error = ret._error;
    } else {
      item.result = 'OK';
    }
  }
  this.body = appUtil.fout(orders);
});